package org.springframework;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.component.DogBean;
import org.springframework.component.TestBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.beans.Introspector;

/**
 * AnnotationConfigApplicationContext 基于注解构建 spring 容器
 * 分为以下几个过程：
 * 1. new AnnotationConfigApplicationContext()
 * 2. super(beanFactory)，super()
 * 3. register(Class<?>... componentClasses)
 * 4. scan(String... basePackages)
 * 5. public void refresh()
 * */
public class AnnotationConfigApplicationContextDemo {

	public static void main(String[] args) {
//		test1();
//		test2();
//		test3();
		test4();
//		test5();
	}

	/**
	 * 无参构造
	 * */
	private static void test1(){

		//无参构造，需要手动调用 register() 和 refresh() 方法
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.register(TestBean.class, DogBean.class);
		context.refresh();

		TestBean bean = context.getBean(TestBean.class);
		bean.helloSpring();
	}

	/**
	 * 参数为一个 DefaultListableBeanFactory，
	 * todo 应该父子容器，目前不是很懂
	 * */
	private static void test2(){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(new DefaultListableBeanFactory());
		context.register(TestBean.class, DogBean.class);
		context.refresh();

		TestBean bean = context.getBean(TestBean.class);
		bean.helloSpring();
	}

	/**
	 * 参数是一堆 class，相当于 AnnotationConfigApplicationContext() + register（） + refresh()，直接就是一个 pojo 类
	 * */
	private static void test3(){
		ApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class, DogBean.class);

		TestBean bean = context.getBean(TestBean.class);
		bean.helloSpring();

		DogBean dog = context.getBean(DogBean.class);
		dog.say();
	}

	/**
	 * 参数是一堆包路径，需要包中的类有 @Component 等注解
	 * */
	private static void test4(){
		ApplicationContext context = new AnnotationConfigApplicationContext("org.springframework.component");

		TestBean bean = context.getBean(TestBean.class);
		bean.helloSpring();

		DogBean dog = context.getBean(DogBean.class);
		dog.say();
	}

	private static void test5(){
		System.out.println( Introspector.decapitalize("Dogtest"));
	}

}
